package com.own.component.util.locate.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.own.component.util.locate.base.LocateMapManager;
import com.own.component.util.locate.model.AmapModel;
import com.own.component.util.locate.model.LocateModel;
import com.own.component.util.locate.property.LocateProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * AmapUtil
 *
 * @author chenxueli
 * @date 2024-02-05 16:38:00
 */
@Component
public class AmapUtil implements LocateMapManager {

    @Resource
    private LocateProperty locateProperty;

    /**
     * 根据关键字获取LocateModel对象信息
     *
     * @param keyword 关键字
     * @return LocateModel 对象信息
     */
    @Override
    public LocateModel getLocateModelByKeyword(String keyword) {
        var map = new HashMap<String, Object>();
        map.put("address", keyword);
        map.put("output", "JSON");
        map.put("key", locateProperty.getKey());
        var request = HttpRequest.get("https://restapi.amap.com/v3/geocode/geo")
                .form(map)
                .execute();
        var body = request.body();
        var object = JSON.parseObject(body);
        request.close();
        if (object.getInteger("status") != 1) {
            return LocateModel.NONE;
        }
        var array = object.getList("geocodes", AmapModel.class);
        if (array.isEmpty()) {
            return LocateModel.NONE;
        }
        var item = array.getFirst();
        var temp = item.getLocation().split(",");
        return new LocateModel(temp[1], temp[0]);
    }

}
